package com.scan.bus;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;

import com.scan.bus.util.Common;
import com.scan.bus.util.LogUtil;

import java.util.LinkedList;
import java.util.Locale;
import java.util.Queue;
import java.util.UUID;


public class SpeechUtilsTest extends Thread{
    private boolean isCommonDone = true;//是否播放完成

    public TextToSpeech textToSpeech; // TTS对象
    private Queue<String> scanData = new LinkedList<>();

    public SpeechUtilsTest(){

    }


    /**
     * tts初始化
     */
    public void initTts(Context context) {
        textToSpeech = new TextToSpeech(context.getApplicationContext(), status -> {// 判断是否转化成功
            if (status == TextToSpeech.SUCCESS) {
                //默认设定语言为中文，原生的android貌似不支持中文。
                int result = textToSpeech.setLanguage(Locale.CHINESE);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Common.staticToast("语音播报失败，请先安装语音引擎");
                } else {
                    textToSpeech.setLanguage(Locale.US);    //不支持中文就将语言设置为英文
                }
                textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                    @Override
                    public void onStart(String utteranceId) {
                        isCommonDone = false;
                    }

                    @Override
                    public void onDone(String utteranceId) {
                        isCommonDone = true;
                    }

                    @Override
                    public void onError(String utteranceId) {
                        isCommonDone = true;
                    }
                });
            }
        });
    }
    public synchronized void speakText(String text) {
        LogUtil.httpLogW("进入播放");
        if (textToSpeech != null) {
            isCommonDone = false;
            boolean isStartPlay = false;
            while(!isCommonDone) {
                LogUtil.httpLogW("开始播放："+isStartPlay);
                if(!isStartPlay) {
                    isStartPlay = true;
                    textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, String.valueOf(UUID.randomUUID()));
                }
                LogUtil.httpLogW("播放状态是否完成："+isCommonDone);
            }
            LogUtil.httpLogW("结束播放");
        }
    }


    public void ttsStop() {
        if (null != textToSpeech) {
            textToSpeech.stop();
        }
    }


    public void ttsDestory() {
        if (null != textToSpeech) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
    }
}